<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools show-page>
        <!-- 使用插槽 -->
        <template #before>
          <span>共{{ page.total }}条数据</span>
        </template>
        <template #after>
          <el-button type="success" @click="$router.push('/import')">Excel 导入</el-button>
          <el-button type="danger" @click="exportData">Excel 导出</el-button>
          <el-button type="primary" @click="isShowAddEmployees = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card>
        <el-table border :data="list">
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{row}" style="width: 120px;">
              <img v-imgerror="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" @click="handle(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <!-- 方式1 使用vue过滤器 -->
          <!-- <el-table-column label="聘用形式" sortable="">
            <template slot-scope="{row}">
              {{ row.formOfEmployment | hireType }}
            </template>
          </el-table-column> -->
          <!-- 方式2 使用element列过滤属性 -->
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" align="center">
            <template v-slot="{row}">
              <el-switch

                :value="row.formOfEmployment === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />

            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>

              <el-button type="text" size="small" @click="roleClick(row.id)">角色</el-button>

              <el-button type="text" size="small" @click="deleteEmployees(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row type="flex" justify="center" align="middle" style="height: 50px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page.sync="page.page"
            :total="page.total"
          >
          </el-pagination>
        </el-row>
      </el-card>

    </div>
    <add-empliyees :is-show-add-employees.sync="isShowAddEmployees" @getEmployeesList="getEmployeesList"></add-empliyees>

    <!-- 二维码弹层 -->
    <el-dialog
      title="二维码"
      :visible.sync="dialogVisible"
      width="30%"
      align="center"
    >

      <canvas ref="myQrcode" />

    </el-dialog>
    <assign-role ref="rolesRef" :show-dialog-visible.sync="showDialogVisible" :user-id="userId"></assign-role>
  </div>
</template>

<script>
import qrcode from 'qrcode'
import { deleteEmployees, getEmployeesList } from '@/api/employees'
import EmployeesEnum from '@/api/constant/employees'
import AddEmpliyees from './components/add-employees'
import { formatDate } from '@/filters'
import AssignRole from './components/assign-role'
export default {
  name: 'Employees',
  components: {
    AddEmpliyees,
    AssignRole
  },
  filters: {
    // 方式1 使用过滤器
    // hireType(val) {
    //   const f = EmployeesEnum.hireType.find(t => t.id === val)
    //   return f ? f.value : '未知'
    // }
  },
  props: {},
  data() {
    return {
      list: [],
      page: {
        page: 1, // 页码 当前处在第几页
        size: 5, // 每页条数 当前页的条数
        total: 0 // 总条数
      },
      isShowAddEmployees: false,
      dialogVisible: false, // 显示打印弹层
      showDialogVisible: false, // 显示角色编辑弹出层
      userId: 0
    }
  },
  watch: {
    // 方式2 使用current-page	的.sync 修饰符事件 监听page.page数据 页码发生改变时请求数据
    'page.page'() {
      this.getEmployeesList()
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    async roleClick(id) {
      this.userId = id // props传值 是异步的
      // 调用子组件定义的获取角色id的方法 使用await是因为需要等到这个异步请求操作完毕再执行下面代码
      await this.$refs.rolesRef.getUserDetaiInfoById(id)
      this.showDialogVisible = true
    },
    handle(url) {
      if (url) {
        this.dialogVisible = true
        this.$nextTick(() => {
          qrcode.toCanvas(this.$refs.myQrcode, url)
        })
      } else {
        this.$message.warning('对不起,没有图片路径')
      }
    },
    // 导出excel
    exportData() {
      import('@/vendor/Export2Excel').then(async excel => {
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const header = Object.keys(headers)
        const values = Object.values(headers)
        const { rows } = await getEmployeesList({
          page: this.page.page,
          size: this.page.total
        })
        const data = rows.map(t => {
          const a = values.map(key => {
            if (key === 'timeOfEntry' || key === 'correctionTime') return formatDate(t[key])
            if (key === 'formOfEmployment') {
              const f = EmployeesEnum.hireType.find(item => item.id === t[key])
              return f ? f.value : '未知'
            }
            return t[key]
          })
          return a
        })
        excel.export_json_to_excel({
          header,
          data,
          filename: '员工工资表',
          autoWidth: true, // 非必填
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2'],
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // // 新增员工
    // addEmployees() {

    // },
    async getEmployeesList() {
      const { total, rows } = await getEmployeesList(this.page)
      this.page.total = total
      this.list = rows
    },
    // 方式1 使用element自带的 页码改变事件 监听页码变化 发起请求
    // changePage(index) {
    //   this.page.page = index
    //   this.getEmployeesList()
    // }

    // 方式2 使用elemnt表格的 formatter方法
    formOfEmployment(row, column, cellValue, index) {
      const f = EmployeesEnum.hireType.find(t => t
        .id === cellValue)
      return f ? f.value : '未知'
    },
    // 删除事件
    deleteEmployees(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        await deleteEmployees(id)
        this.$message.success('删除成功!')
        this.getEmployeesList()
      }).catch(() => {

      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
